package com.hci.pwf;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;

public class AlarmReceiver extends BroadcastReceiver {
	public static final String ALARM_ALERT = "com.hci.pwf.ALARM_ALERT";
	private MediaPlayer mediaPlayer;
	private NotificationManager notificationManager;
	boolean defaultAlarmSetting=false;
	private Context context;
	@Override
	public void onReceive(Context context, Intent intent) {
		// start to play the music,
		// show a notification
		// run the application
		boolean alarmOrNot=intent.getBooleanExtra("AlarmOrNot", defaultAlarmSetting);
		this.context=context;
		notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		//show notification
		 // Text to display in the status bar when the notification is launched
		  String tickerText = "you have new Weather Inforamtion, please check it!";
		  
		  // The extended status bar orders notification in time order
		  long when = System.currentTimeMillis();
		  Notification notification = new Notification( R.drawable.icon,tickerText, when);
		  
		 // Context context = getApplicationContext();
		  
		  // Text to display in the extended status window
		  String expandedText = "Read new Weather Message!";
		  
		  // Title for the expanded status
		  String expandedTitle = "new Weather Information";
		  
		  // Intent to launch an activity when the extended text is clicked
		  Intent it = new Intent(context, MainActivity.class);
		  PendingIntent launchIntent = PendingIntent.getActivity(context, 0, it, 0);
		  notification.setLatestEventInfo(context,expandedTitle,expandedText,
		 launchIntent);
		  notification.number++;
		  int notificationRef = 1;
		  notificationManager.notify(notificationRef, notification);
         //player music
		  killMediaPlayer();
		if (alarmOrNot){
		try {
			play(R.raw.ring);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	}
	private void play(int resourceID) throws Exception {
		mediaPlayer = MediaPlayer.create(context, resourceID);
		mediaPlayer.start();
	}

	private void killMediaPlayer() {
		if (mediaPlayer != null) {
			try {
				mediaPlayer.release();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
		

	}


